import { Box, SxProps, styled } from "@mui/system";
import { Form, Checkbox, Input, Button, Dialog, FormProps, ButtonProps } from "antd-mobile";
import React, { useImperativeHandle, useRef } from "react";
const StyledForm = styled(Form)(({ theme: any }) => ({}));
import AFormItem from "./AFormItem";
import { FormInstance } from "antd-mobile/es/components/form";
interface FormActionButtonProps extends Omit<ButtonProps, "onClick"> {
  children?: any | null;
}
export interface FooterOptions {
  okButton?: FormActionButtonProps;
  cancelButton?: FormActionButtonProps;
}
export interface AFormProps extends FormProps {
  onSubmit?: (data: any, form: FormInstance) => void; //内置提交按钮提交时触发
  onCancel?: (data: any, form: FormInstance) => void; //内置取消按钮取消时触发
  children?: any;
  footerOptions?: FooterOptions | null; //默认会有footer，null则去除
}
export default React.forwardRef(({ onSubmit, footer, children, footerOptions, onCancel, ...otr }: AFormProps, ref) => {
  const onFinish = (values: any) => {};
  const [form] = Form.useForm();
  const _onSubmit = () => {
    form.validateFields().then((res) => {
      onSubmit && onSubmit(form.getFieldsValue(), form);
    });
  };
  const _onCancel = () => {
    form.validateFields().then((res) => {
      onCancel && onCancel(form.getFieldsValue(), form);
    });
  };
  useImperativeHandle(
    ref,
    () => ({
      instance: form,
    }),
    [form]
  );
  return (
    <Box ref={ref}>
      <StyledForm form={form} layout='horizontal' onFinish={onFinish} {...otr}>
        {children}
        {footer === null ? (
          ""
        ) : (
          <AFormItem>
            <Box sx={{ width: "100%", display: "flex", flexDirection: "column" }}>
              <Button color='primary' style={{ marginBottom: 16 }} {...footerOptions?.okButton} onClick={_onSubmit}>
                {footerOptions?.okButton?.children === null ? null : footerOptions?.okButton?.children || "确认"}
              </Button>
              <Button color='default' {...footerOptions?.cancelButton} onClick={_onCancel}>
                {footerOptions?.cancelButton?.children === null ? null : footerOptions?.cancelButton?.children || "取消"}
              </Button>
            </Box>
          </AFormItem>
        )}
      </StyledForm>
    </Box>
  );
});
